# -*- coding: utf-8 -*-

### Imports ###
import xbmc
import re
import urllib
from common import *
from common import (_addon, fav__COMMON__list_fetcher)

### ##########################################################################
### ##########################################################################
SiteName = 'Anime-Centrum [Anime]'
SiteTag = 'anime-centrum'
mainSite = 'http://anime-centrum.net/'

__settings__ = xbmcaddon.Addon(id="plugin.video.anime-centrum")
addonPath = __settings__.getAddonInfo('path')
iconSite = addonPath + '/art/icon.png'

fanartSite = addonPath + '/art/fanart2.png'
colors = {'0': 'white', '1': 'red', '2': 'blue', '3': 'green', '4': 'yellow', '5': 'orange', '6': 'lime', '7': '', '8': 'cornflowerblue', '9': 'blueviolet', '10': 'hotpink', '11': 'pink', '12': 'tan'}

CR = '[CR]'
MyAlphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
MyBrowser = ['User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3']
### #########################################################################
### #########################################################################
site = addpr('site', '')
section = addpr('section', '')
url = addpr('url', '')
sections = {'series': 'series', 'movies': 'movies'}
thumbnail = addpr('img', '')
fanart = addpr('fanart', '')
page = addpr('page', '')

### #########################################################################


def Browse_Page(url, page='', metamethod=''):
    html = nURL(url)
    Browse_Items(html, metamethod)
    eod()


def Browse_Items(html, metamethod='', content='tvshows', view='515'):
    if (len(html) == 0):
        return
    r = re.compile('<a href="http://anime-centrum.net/(.+?)" class="tip-(.+?) tip-style-2"').findall(html)
    ItemCount = len(r)
    if len(r) > 0:
        for _url, _x in r:
            strona = 'http://anime-centrum.net/' + _url
            html2 = nURL(strona)
#  nazwa
            tytul = re.compile('<meta property="og:title" content="(.+?)" />').findall(html2)
            ItemCount = len(tytul)
            if len(tytul) > 0:
                for _tytul in tytul:
                    _name2 = _tytul.encode('utf-8')
#  grafika
            image = re.compile('<meta property="og:image" content="(.+?)" />').findall(html2)
            ItemCount = len(image)
            if len(image) > 0:
                for foto in image:
                    img = foto
            else:
                img = ""
#  fanart
            image2 = re.compile('<!--dle_image_begin:(.+?)</a><!--dle_image_end-->').findall(html2)
            ItemCount = len(image2)
            if len(image2) > 0:
                for foto2 in image2:
                    strona2 = foto2
                    image3 = re.compile('http:(.+?).jpg').findall(strona2)
                    ItemCount = len(image3)
                    if len(image3) > 0:
                        for foto3 in image3:
                            fanart = "http:" + foto3 + ".jpg"
            else:
                fanart = img
#  opis
            opis = re.compile('<strong>Opis:</strong>(.+)').findall(html2)
            ItemCount = len(opis)
            if len(opis) > 0:
                for desc in opis:
                    plot = desc
            labs = {}
            try:
                labs['plot'] = plot
            except:
                labs['plot'] = ''
###
            pars = {'mode': 'Episodes', 'site': site, 'section': section, 'title': _name2, 'url': strona, 'img': img, 'fanart': fanart}
            contextLabs = {'title': _name2, 'url': strona, 'img': img, 'fanart': fanart, 'todoparams': _addon.build_plugin_url(pars), 'site': site, 'section': section, 'plot': labs['plot']}
            if   section == 'movie':
                contextMenuItems = ContextMenu_Movies(contextLabs)
            elif section == 'series':
                contextMenuItems = ContextMenu_Series(contextLabs)
            else:
                contextMenuItems = []
            labs['title'] = _name2
            _addon.add_directory(pars, labs, is_folder=True, fanart=fanart, img=img, contextmenu_items=contextMenuItems, total_items=ItemCount)
    set_view(content, view_mode=addst('tvshows-view'))

# listowanie odcinkow
def Browse_Episodes(url,page='',content='episodes',view='515'):
    if url == '':
        return
    html = nURL(url)
    html = messupText(html, True, True)
    s = '<a href="http://(.+?)">Odcinek(.+?)</a>'
    matches = re.compile(s).findall(html)
    ItemCount = len(matches)
    if ItemCount > 0:
        for _url, _nazwa in matches:
            _url2 = 'http://' + urllib.quote(_url)
            _name = 'Odcinek' + _nazwa
            _title = '' + cFL_(_name)
#  grafika
            image = re.compile('<meta property="og:image" content="(.+?)" />').findall(html)
            ItemCount = len(image)
            if len(image) > 0:
                for foto in image:
                    img = foto
            else:
                img = ""
#  fanart
            image2 = re.compile('<!--dle_image_begin:(.+?)</a><!--dle_image_end-->').findall(html)
            ItemCount = len(image2)
            if len(image2) > 0:
                for foto2 in image2:
                    strona2 = foto2
                    image3 = re.compile('http:(.+?).jpg').findall(strona2)
                    ItemCount = len(image3)
                    if len(image3) > 0:
                        for foto3 in image3:
                            fanart = "http:" + foto3 + ".jpg"
            else:
                fanart = img
#  opis
            opis = re.compile('<strong>Opis:</strong>(.+)').findall(html)
            ItemCount = len(opis)
            if len(opis) > 0:
                for desc in opis:
                    plot = desc
            labs = {}
            try:
                labs['plot'] = plot
            except:
                labs['plot'] = ''
#  wyciąganie linku do mp4
            html2 = nURL(_url2)
            _link = re.compile("<source src='(.+?)' type='video/mp4' />").findall(html2)
            ItemCount = len(_link)
            if len(_link) > 0:
                for link in _link:
                    strona = link.replace(' ', '%20')
###
            contextLabs = {'title': _name, 'year': '0000', 'url': _url2, 'img': img, 'fanart': fanart, 'DateAdded': '', 'plot': labs['plot']}
            contextMenuItems = ContextMenu_Episodes(labs=contextLabs)
            pars = {'mode': 'PlayFromHost', 'site': site, 'section': section, 'title': _name, 'url': strona, 'img': img, 'fanart': fanart}
            labs['title'] = _title
            _addon.add_directory(pars, labs, is_folder=False, fanart=fanart, img=img, contextmenu_items=contextMenuItems, total_items=ItemCount)
    set_view(content, int(addst('links-view')))
    eod()

#  lista ABC
def Browse_AZ():
    if section == 'series':
        tUrl = mainSite + 'anime-online/'
        scolor = colors['2']
        _addon.add_directory({'mode': 'Page', 'site': site, 'section': section, 'url': tUrl + 'others'}, {'title': cFL_('#', scolor)}, is_folder=True, fanart=fanartSite, img=iconSite)
        for az in MyAlphabet:
            _addon.add_directory({'mode': 'Page', 'site': site, 'section': section, 'url': tUrl + az + '.html'}, {'title': cFL_(az.upper(), scolor)}, is_folder=True, fanart=fanartSite, img=addonPath + '/art/'+ az +'.png')
    set_view('list', view_mode=addst('default-view'))
    eod()

#  ulubione
def Fav_List(site='',section='',subfav=''):
    debob(['test1',site,section,subfav])
    favs=fav__COMMON__list_fetcher(site=site,section=section,subfav=subfav)
    ItemCount=len(favs)
    debob('test2 - '+str(ItemCount))
    if len(favs)==0: myNote('Favorites','None Found'); eod(); return
    debob(favs)
    for (_name,_year,_img,_fanart,_Country,_Url,_plot,_Genres,_site,_subfav,_section,_ToDoParams,_commonID,_commonID2) in favs:
        if _img > 0: img=_img
        else: img=iconSite
        if _fanart > 0: fimg=_fanart
        else: fimg=fanartSite
        debob('_ToDoParams'); debob(_ToDoParams)
        pars=_addon.parse_query(_ToDoParams)
        debob('pars'); debob(pars)
        _title=cFL_(_name,'white')
        if (len(_year) > 0) and (not _year=='0000'): _title+=cFL('  ('+cFL(_year,'deeppink')+')','pink')
        if len(_Country) > 0: _title+=cFL('  ['+cFL(_Country,'deeppink')+']','pink')

        contextLabs={'title':_name,'year':_year,'img':_img,'fanart':_fanart,'country':_Country,'url':_Url,'plot':_plot,'genres':_Genres,'site':_site,'subfav':_subfav,'section':_section,'todoparams':_ToDoParams,'commonid':_commonID,'commonid2':_commonID2}
        ##contextLabs={'title':_name,'year':'0000','url':_url,'img':img,'fanart':fimg,'DateAdded':'','todoparams':_addon.build_plugin_url(pars),'site':site,'section':section}
        contextMenuItems=ContextMenu_Favorites(contextLabs)
        #contextMenuItems=[]
        _addon.add_directory(pars,{'title':_title,'plot':_plot},is_folder=True,fanart=fimg,img=img,total_items=ItemCount,contextmenu_items=contextMenuItems)
        #
    #
    if 'movie' in section.lower(): content='movies'
    else: content='tvshows'
    set_view(content,view_mode=int(addst('tvshows-view'))); eod()


def SubMenu():
    if section == 'series':
        _addon.add_directory({'mode': 'AZ', 'site': site, 'section': section}, {'title': "Lista anime A-Z."}, is_folder=True, fanart=fanartSite, img=iconSite)
# ulubione
        _addon.add_directory({'mode': 'FavoritesList', 'site': site, 'section': section}, {'title': cFL_(ps('WhatRFavsCalled') + addst('fav.tv.1.name'), ps('cFL_color3'))}, fanart=fanartSite, img=iconSite)
        _addon.add_directory({'mode': 'FavoritesList', 'site': site, 'section': section, 'subfav': '2'}, {'title': cFL_(ps('WhatRFavsCalled') + addst('fav.tv.2.name'), ps('cFL_color3'))}, fanart=fanartSite, img=iconSite)
        _addon.add_directory({'mode': 'FavoritesList', 'site': site, 'section': section, 'subfav': '3'}, {'title': cFL_(ps('WhatRFavsCalled') + addst('fav.tv.3.name'), ps('cFL_color3'))}, fanart=fanartSite, img=iconSite)
        _addon.add_directory({'mode': 'FavoritesList', 'site': site, 'section': section, 'subfav': '4'}, {'title': cFL_(ps('WhatRFavsCalled') + addst('fav.tv.4.name'), ps('cFL_color3'))}, fanart=fanartSite, img=iconSite)
    set_view('list', view_mode=addst('default-view'))
    eod()


def SectionMenu():
        _addon.add_directory({'mode': 'SubMenu', 'site': site, 'section': 'series'}, {'title': 'Anime Series'}, is_folder=True, fanart=fanartSite, img=iconSite)
        set_view('list', view_mode=addst('default-view'))
        eod()


### ############################################################################################################
def mode_subcheck(mode='',site='',section='',url=''):
    deb('mode',mode);
    if (mode=='SectionMenu'):         SectionMenu()
    elif (mode=='') or (mode=='main') or (mode=='MainMenu'): SectionMenu()
    elif (mode=='SubMenu'):             SubMenu()
    elif (mode=='Page'):                     Browse_Page(url=url,page=page,metamethod=addpr('metamethod','')) #(site,section)
    elif (mode=='Episodes'):             Browse_Episodes(url,page)


    elif (mode=='AZ'):                         Browse_AZ()

    elif (mode=='PlayFromHost'):     PlayFromHost(url)

    elif (mode=='FavoritesList'): Fav_List(site=site,section=section,subfav=addpr('subfav',''))
    ##

    elif (mode=='PlayFromHost'):                 PlayFromHost(url)
    elif (mode=='ResolverSettings'):         import urlresolver; urlresolver.display_settings()  ## Settings for UrlResolver script.module.


    elif (mode=='cFavoritesEmpty'):      fav__COMMON__empty( site=site,section=section,subfav=addpr('subfav','') ); xbmc.executebuiltin("XBMC.Container.Refresh");
    elif (mode=='cFavoritesRemove'):  fav__COMMON__remove( site=site,section=section,subfav=addpr('subfav',''),name=addpr('title',''),year=addpr('year','') )
    elif (mode=='cFavoritesAdd'):          fav__COMMON__add( site=site,section=section,subfav=addpr('subfav',''),name=addpr('title',''),year=addpr('year',''),img=addpr('img',''),fanart=addpr('fanart',''),plot=addpr('plot',''),commonID=addpr('commonID',''),commonID2=addpr('commonID2',''),ToDoParams=addpr('todoparams',''),Country=addpr('country',''),Genres=addpr('genres',''),Url=url ) #,=addpr('',''),=addpr('','')
    elif (mode=='AddVisit'):
        try: visited_add(addpr('title')); RefreshList();
        except: pass
    elif (mode=='RemoveVisit'):
        try: visited_remove(addpr('title')); RefreshList();
        except: pass
    elif (mode=='EmptyVisit'):
        try: visited_empty(); RefreshList();
        except: pass
    elif (mode=='refresh_meta'):            refresh_meta(addpr('video_type',''),TagAnimeName(addpr('title','')),addpr('imdb_id',''),addpr('alt_id',''),addpr('year',''))
    else: myNote(header='Site:  "'+site+'"',msg=mode+' (mode) not found.'); import mMain
    #

mode_subcheck(addpr('mode',''),addpr('site',''),addpr('section',''),addpr('url',''))
### ############################################################################################################
### ############################################################################################################
